const db = require('../config/database');
const bcrypt = require('bcrypt');
const logger = require('../config/logger');

/**
 * 获取所有用户列表
 */
exports.getUserList = async (req, res) => {
  try {
    const { page = 1, limit = 10, keyword = '', status = '' } = req.query;
    const offset = (page - 1) * limit;

    let query = `
      SELECT
        u.id,
        u.username,
        u.email,
        u.avatar_url,
        u.client_id,
        u.status,
        u.is_online,
        u.last_online_at,
        u.last_ip,
        u.created_at,
        u.updated_at
      FROM users u
      WHERE u.deleted_at IS NULL
    `;

    let countQuery = 'SELECT COUNT(*) as total FROM users WHERE deleted_at IS NULL';
    const params = [];

    // 状态筛选
    if (status) {
      query += ' AND u.status = ?';
      countQuery += ' AND status = ?';
      // 🔥 转换状态：字符串 → 数字用于查询
      const statusValue = (status === 'active' || status === 'enabled' || status === 1) ? 1 : 0;
      params.push(statusValue);
    }

    // 搜索条件
    if (keyword) {
      query += ' AND (u.username LIKE ? OR u.email LIKE ?)';
      countQuery += ' AND (username LIKE ? OR email LIKE ?)';
      params.push(`%${keyword}%`, `%${keyword}%`);
    }

    // 获取总数
    const [countResult] = await db.query(countQuery, params);
    const total = countResult[0].total;

    // 分页查询
    query += ' ORDER BY u.created_at DESC LIMIT ? OFFSET ?';
    const [users] = await db.query(query, [...params, parseInt(limit), offset]);

    // 🔥 转换状态：数字 → 字符串返回给前端
    const formattedUsers = users.map(user => ({
      ...user,
      status: user.status === 1 ? 'active' : 'disabled'
    }));

    res.json({
      success: true,
      data: {
        users: formattedUsers,
        total,
        page: parseInt(page),
        limit: parseInt(limit)
      }
    });
  } catch (error) {
    logger.error('获取用户列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户列表失败'
    });
  }
};

/**
 * 创建用户
 */
exports.createUser = async (req, res) => {
  try {
    const { username, password, email, client_id, status = 'active' } = req.body;

    // 检查用户名是否存在
    const [existing] = await db.query(
      'SELECT id FROM users WHERE username = ? AND deleted_at IS NULL',
      [username]
    );

    if (existing.length > 0) {
      return res.status(400).json({
        success: false,
        message: '用户名已存在'
      });
    }

    // 加密密码
    const hashedPassword = await bcrypt.hash(password, 10);

    // 生成客户端ID（如果没有提供）
    const finalClientId = client_id || `CLIENT_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

    // 🔥 转换状态：字符串 → 数字（数据库是tinyint）
    const statusValue = (status === 'active' || status === 'enabled' || status === 1) ? 1 : 0;

    // 创建用户
    const [result] = await db.query(
      `INSERT INTO users (username, password, email, client_id, status, created_by)
       VALUES (?, ?, ?, ?, ?, ?)`,
      [username, hashedPassword, email, finalClientId, statusValue, req.user?.id || null]
    );

    logger.info(`管理员创建用户 ${username}`);

    res.json({
      success: true,
      message: '用户创建成功',
      data: {
        id: result.insertId,
        username,
        email,
        client_id: finalClientId
      }
    });
  } catch (error) {
    logger.error('创建用户失败:', error);
    res.status(500).json({
      success: false,
      message: '创建用户失败'
    });
  }
};

/**
 * 更新用户
 */
exports.updateUser = async (req, res) => {
  try {
    const { id } = req.params;
    const { email, client_id, status } = req.body;

    const updates = [];
    const params = [];

    if (email !== undefined) {
      updates.push('email = ?');
      params.push(email);
    }

    if (client_id !== undefined) {
      updates.push('client_id = ?');
      params.push(client_id);
    }

    if (status !== undefined) {
      updates.push('status = ?');
      // 🔥 转换状态：字符串 → 数字（数据库是tinyint）
      const statusValue = (status === 'active' || status === 'enabled' || status === 1) ? 1 : 0;
      params.push(statusValue);
    }

    if (updates.length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有要更新的内容'
      });
    }

    params.push(id);
    await db.query(
      `UPDATE users SET ${updates.join(', ')}, updated_at = NOW() WHERE id = ? AND deleted_at IS NULL`,
      params
    );

    logger.info(`管理员更新用户 ID:${id}`);

    res.json({
      success: true,
      message: '用户更新成功'
    });
  } catch (error) {
    logger.error('更新用户失败:', error);
    res.status(500).json({
      success: false,
      message: '更新用户失败'
    });
  }
};

/**
 * 删除用户
 */
exports.deleteUser = async (req, res) => {
  try {
    const { id } = req.params;

    // 软删除
    await db.query(
      'UPDATE users SET deleted_at = NOW() WHERE id = ? AND deleted_at IS NULL',
      [id]
    );

    logger.info(`管理员删除用户 ID:${id}`);

    res.json({
      success: true,
      message: '用户删除成功'
    });
  } catch (error) {
    logger.error('删除用户失败:', error);
    res.status(500).json({
      success: false,
      message: '删除用户失败'
    });
  }
};

/**
 * 批量删除用户
 */
exports.batchDeleteUsers = async (req, res) => {
  try {
    const { ids } = req.body;

    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请提供要删除的用户ID列表'
      });
    }

    const placeholders = ids.map(() => '?').join(',');
    await db.query(
      `UPDATE users SET deleted_at = NOW() WHERE id IN (${placeholders}) AND deleted_at IS NULL`,
      ids
    );

    logger.info(`管理员批量删除用户，数量: ${ids.length}`);

    res.json({
      success: true,
      message: `成功删除 ${ids.length} 个用户`
    });
  } catch (error) {
    logger.error('批量删除用户失败:', error);
    res.status(500).json({
      success: false,
      message: '批量删除用户失败'
    });
  }
};

/**
 * 修改用户状态
 */
exports.updateUserStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status } = req.body;

    if (!['active', 'disabled', 0, 1].includes(status)) {
      return res.status(400).json({
        success: false,
        message: '无效的状态值'
      });
    }

    // 🔥 转换状态：字符串 → 数字（数据库是tinyint）
    const statusValue = (status === 'active' || status === 'enabled' || status === 1) ? 1 : 0;

    await db.query(
      'UPDATE users SET status = ?, updated_at = NOW() WHERE id = ? AND deleted_at IS NULL',
      [statusValue, id]
    );

    logger.info(`管理员修改用户 ID:${id} 状态为 ${status}`);

    res.json({
      success: true,
      message: '状态修改成功'
    });
  } catch (error) {
    logger.error('修改用户状态失败:', error);
    res.status(500).json({
      success: false,
      message: '修改用户状态失败'
    });
  }
};

/**
 * 重置用户密码
 */
exports.resetUserPassword = async (req, res) => {
  try {
    const { id } = req.params;
    const { password } = req.body;

    if (!password || password.length < 6) {
      return res.status(400).json({
        success: false,
        message: '密码长度至少为6个字符'
      });
    }

    const hashedPassword = await bcrypt.hash(password, 10);

    await db.query(
      'UPDATE users SET password = ?, updated_at = NOW() WHERE id = ? AND deleted_at IS NULL',
      [hashedPassword, id]
    );

    logger.info(`管理员重置用户 ID:${id} 的密码`);

    res.json({
      success: true,
      message: '密码重置成功'
    });
  } catch (error) {
    logger.error('重置密码失败:', error);
    res.status(500).json({
      success: false,
      message: '重置密码失败'
    });
  }
};

/**
 * 获取用户详情
 */
exports.getUserDetail = async (req, res) => {
  try {
    const { id } = req.params;

    const [users] = await db.query(
      'SELECT id, username, email, nickname, avatar_url, status, is_online, last_online_at, last_ip, created_at FROM users WHERE id = ?',
      [id]
    );

    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    // 获取用户统计信息
    const [stats] = await db.query(
      'SELECT * FROM v_user_transfer_stats WHERE user_id = ?',
      [id]
    );

    res.json({
      success: true,
      data: {
        ...users[0],
        stats: stats[0] || {}
      }
    });
  } catch (error) {
    logger.error('获取用户详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取用户详情失败'
    });
  }
};

/**
 * 用户修改自己的密码
 */
exports.changePassword = async (req, res) => {
  try {
    const userId = req.user.id;
    const { oldPassword, newPassword } = req.body;

    // 验证旧密码
    const [users] = await db.query(
      'SELECT password FROM users WHERE id = ?',
      [userId]
    );

    if (users.length === 0) {
      return res.status(404).json({
        success: false,
        message: '用户不存在'
      });
    }

    const isPasswordValid = await bcrypt.compare(oldPassword, users[0].password);
    if (!isPasswordValid) {
      return res.status(400).json({
        success: false,
        message: '当前密码错误'
      });
    }

    // 加密新密码
    const hashedPassword = await bcrypt.hash(newPassword, 10);

    // 更新密码
    await db.query(
      'UPDATE users SET password = ?, updated_at = NOW() WHERE id = ?',
      [hashedPassword, userId]
    );

    logger.info(`用户修改密码: ${userId}`);

    res.json({
      success: true,
      message: '密码修改成功'
    });
  } catch (error) {
    logger.error('修改密码失败:', error);
    res.status(500).json({
      success: false,
      message: '修改密码失败'
    });
  }
};

/**
 * 用户更新自己的头像
 */
exports.updateAvatar = async (req, res) => {
  try {
    const userId = req.user.id;
    const { avatar_url } = req.body;

    if (!avatar_url) {
      return res.status(400).json({
        success: false,
        message: '请提供头像URL'
      });
    }

    // 更新头像
    await db.query(
      'UPDATE users SET avatar_url = ?, updated_at = NOW() WHERE id = ?',
      [avatar_url, userId]
    );

    logger.info(`用户更新头像: ${userId}`);

    res.json({
      success: true,
      message: '头像更新成功',
      data: {
        avatar_url
      }
    });
  } catch (error) {
    logger.error('更新头像失败:', error);
    res.status(500).json({
      success: false,
      message: '更新头像失败'
    });
  }
};
